<?php
namespace app\index\controller;

use app\common\controller\Frontend;
use EasyWeChat\Factory;
use fast\Random;
use think\Config;
use think\Db;
use think\Session;

class Form extends Frontend
{


    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $noNeedWechat = ['oauth','wechathandle','success','error'];
    protected $layout = 'form';
    protected $app;

    public function _initialize()
    {
        parent::_initialize();
        $action = $this -> request -> action();
        $controller = $this -> request -> controller();

        $config = array_merge(Config::get('wechatConfig'),[
                'oauth' => [
                    'scopes'   => ['snsapi_userinfo'],
                    'callback' => url('/index/'.$controller.'/wechathandle'),
                ],
            ]
        );
        $this -> app = Factory::officialAccount($config);

        if(
            defined('CHECKWECHAT')
            && CHECKWECHAT
            && (is_null(Session::get('wechatUser'))
                || !isset(Session::get('wechatUser')['openid'])
                || is_null(Session::get('wechatUser')['openid'])
                || Session::get('wechatUser')['openid'] == ''
            )
            && !in_array($action,$this -> noNeedWechat)
            && !$this -> request -> isPost()
        ){
            Session::set('redirectUrl',$_SERVER['REQUEST_URI']);
            $this -> redirect(url('oauth'));
        }
        if(defined('CHECKWECHAT') && CHECKWECHAT){
            $wechatUser = Session::get('wechatUser');
            $openid = '';
            if(isset($wechatUser['openid'])){
                $openid = Session::get('wechatUser')['openid'];
            }else{
                Session::delete('wechatUser');
//                header('Location: https://yqsb.qau.edu.cn/index/oside');
            }

            $user = \app\admin\model\User::getByOpenid($openid);

//            if($this -> request -> action() == 'report2'){
//                print_r(Session::get('wechatUser'));
//            }

            if(is_null($user)){
                $u = Session::get('wechatUser');
                $extend = [
                    'openid'    => $u['openid'],
                    'is_sub'    => $u['subscribe'],
                    'password'  => md5(md5('123456').'syzdts'),
                    'salt'      => 'syzdts',
                    'g_id'       => 0,
                    'group_id'  => 1,
                    'createtime'   => time(),
                    'updatetime'    => time(),
//                    'email'     => Random::alnum().Random::alnum().'@163.com'
                ];

                if(isset($u['headimgurl'])){
                    $extend['headimgurl'] = $u['headimgurl'];
                }
                if(isset($u['nickname'])){
                    $extend['nickname'] = $extend['username'] = $u['nickname'];
                }

                $id = Db::name('user') -> insertGetId($extend);
                $us = \app\admin\model\User::get($id);
                if($us){
                    $user = $us;
                }
            }
            halt($user);
            Session::set('frontUser',$user);
            $is_sub = $user ? $user['is_sub']:1;
            $this->assign('is_sub',$is_sub);
            // $this->assignconfig("user",['is_sub'=>$user['is_sub']]);
            // Session::delete('wechatUser');
        }
        // $this->assignconfig("user",['is_sub'=>1]);
        // $this->assign('is_sub',1);
    }



    public function oauth(){
        $oauth = $this -> app->oauth;

        $response = $oauth->scopes(['snsapi_userinfo'])
            ->redirect();
        $response -> send();
    }

    public function wechathandle(){
        $oauth = $this -> app->oauth;

        $_user = $oauth -> user() -> toArray();
        $_userw = $this -> app -> user->get($_user['id']);

        Session::set('wechatUser',$_userw);
        $user = \app\admin\model\User::getByOpenid($_user['id']);
        if(!$user){
            $extend = [
                'openid'    => $_user['id'],
                'headimgurl'    => $_user['original']['headimgurl'],
                'sex'       => $_user['original']['sex'],
                'city'      => $_user['original']['city'],
                'province'  => $_user['original']['province'],
                'country'    => $_user['original']['country'],
                'is_sub'    => $_userw['subscribe']
            ];
            $this->auth->register($_user['name'], '123456', Random::alnum().Random::alnum().'@163.com', '',$extend);
        }else{
            $user -> is_sub = $_userw['subscribe'];
            $user -> save();
        }

        $url = Session::get('redirectUrl') ? Session::get('redirectUrl') : url('index');
        $this -> redirect($url);
    }

}
